package gr.handmademarket.bl.operations;

import gr.handmademarket.hibernate.HibernateUtil;
import gr.handmademarket.po.implementations.Product;
import gr.handmademarket.po.implementations.Seller;
import gr.handmademarket.po.interfaces.Category;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * operation for fetching products.
 */
public class LoadProductsOperation {

	/**
	 * Creates a new LoadProductsOperation object. 
	 *
	 */
	public LoadProductsOperation(){
		// empty
	}
	
	/**
	 * the products to be fetched.
	 */
	private List<Product> products =  new ArrayList<Product>();
	
	/**
	 * the category.
	 */
	private Category category;
	
	/**
	 * 
	 */
	@SuppressWarnings({ "unchecked", "nls" })
	public void execute(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery(createHqlString());
		if (category instanceof Seller){
			query.setString("user", ((Seller) category).getUsername());
		}
		products = query.list();
	}
	
	/**
	 * Gets the products.
	 *
	 * @return Returns the products
	 */
	public List<Product> getProducts() {
		return products;
	}
	
	/**
	 * Assigns a new value to the category.
	 *
	 * @param category the category to set
	 */
	public void setCategory(Category category) {
		this.category = category;
	}
	
	/**
	 * @return hql.
	 */
	@SuppressWarnings("nls")
	private String createHqlString(){
		String hql = "select p from Product p ";
		if (category != null){
			if (category instanceof Seller){
				hql += " join p.seller s where s.username = :user ";
			}else{
				hql += " join p.category c where c.code = " + category.getCode();
			}
		}
		hql += " order by p.code desc ";
		return hql;
	}
	
}
